<template>
  <div class="app-container">
    <div>
      <el-button type="primary" icon="el-icon-plus" @click="handleOpen()">新增</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="handleMultipartDelete()">删除</el-button>
    </div>

    <el-table
      ref="multipleTable"
      :data="attrList"
      border
      tooltip-effect="dark"
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="55"
        align="center"
        sortable
        :index="indexMethod">
      </el-table-column>
      <el-table-column
        prop="name"
        align="center"
        label="字段名称">
      </el-table-column>
      <el-table-column
        prop="describe"
        align="center"
        label="字段描述">
      </el-table-column>
      <el-table-column
        prop="sort"
        align="center"
        label="排序"
        width="100">
      </el-table-column>
      <el-table-column
        label="字段状态"
        align="center"
        width="100">
        <template slot-scope="scope">
          {{ scope.row.status === '1' ? '开启' : '停止' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        align="center"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleUpdate(scope.row.id)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.page + 1"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="query.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total" style="float: right; margin-top: 20px;">
    </el-pagination>

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入字段名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段描述" prop="describe">
              <el-input v-model="form.describe" placeholder="请输入字段描述" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio key="1" label="1">启用</el-radio>
                <el-radio key="0" label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">确 定</el-button>
        <el-button @click="handleCancel()">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAttr, getAttr, addAttr, updateAttr, delAttr, getCountByName } from '@/api/camunda/attr'

export default {
  name: "index",
  data() {
    return {
      attrList: [],
      multiple: [],
      query: {
        page: 0,
        size: 10
      },
      total: 0,

      title: '',
      repName: 0,
      open: false,
      form: {
        id: undefined,
        name: '',
        describe: '',
        status: '1',
        sort: 0
      },
      rules: {
        name: [
          {required: true, trigger: "blur", validator: this.nameRules}
        ],
        describe: [
          {required: true, message: "字段描述不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '字段描述长度必须介于 2 和 20 之间', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init(){
      // 初始化数据模型列表
      listAttr(this.query)
        .then(({data}) => {
          this.total = data.total
          this.attrList = data.rows
        }).catch()
    },
    indexMethod(index) {
      const sum = this.query.size * (this.query.page)
      return index + sum + 1
    },
    handleCurrentChange(val) {
      this.query.page = val - 1
      this.init()
    },
    handleSizeChange(val) {
      this.query.size = val
      this.init()
    },
    handleSelectionChange(val) {
      this.multiple = val;
    },
    handleOpen() {
      this.reset()
      this.title = '新增'
      this.open = true
    },
    handleCancel() {
      this.reset()
      this.open = false
    },
    reset() {
      this.form = {
        id: undefined,
        name: '',
        describe: '',
        status: '1',
        sort: 0,
        createTime: null,
        updateTime: null
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateAttr(this.form)
              .then(() => {
                this.$message({type: 'success', message: '修改成功!'})
                this.open = false;
                this.init();
              }).catch(() => {this.$message({type: 'error', message: '修改失败!'})})
          } else {
            addAttr(this.form)
              .then(() => {
                this.$message({type: 'success', message: '添加成功!'})
                this.open = false;
                this.init();
              }).catch(() => {this.$message({type: 'error', message: '添加失败!'})})
          }
        }
      });
    },
    handleMultipartDelete() {
      const ids = []
      this.multiple.forEach((item) => {
        ids.push(item.id)
      })

      this.$confirm('共选中'+ ids.length +'项，此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAttr(ids)
          .then(() => {
            this.$message({type: 'success', message: '删除成功!'})
            this.init();
          }).catch(() => {this.$message({type: 'error', message: '删除失败!'})})
      }).catch()
    },
    handleUpdate(id) {
      this.reset()
      this.title = '修改'
      getAttr(id)
        .then(({data}) => {
          this.form = data
          this.open = true
        }).catch()
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAttr(id)
          .then(() => {
            this.$message({type: 'success', message: '删除成功!'})
            this.init();
          }).catch(() => {this.$message({type: 'error', message: '删除失败!'})})
      }).catch(() => {})
    },
    nameRules(rule, value, callback) {
      if (value.length < 2 || value.length > 10) {
        callback(new Error('字段名称长度必须介于 2 和 10 之间'))
      } else {
        let promiseList = []
        const promise = getCountByName(this.form)
          .then(({data}) => {
            if(data === 0){
              callback()
            } else {
              callback(new Error('字段名称已存在'))
            }
          }).catch(() => {
            callback(new Error('服务器异常'))
          })
        promiseList.push(promise)

        Promise.all(promiseList).then(() => {
          callback()
        }).catch()
      }
    }
  }
}
</script>

<style scoped>

</style>
